import React, {useState} from 'react';
import RoomTable from './RoomTable';
import {PlusOutlined} from '@ant-design/icons';
import {Button, Modal, Form, Input, Select, message, Upload} from 'antd';
import axios from '../../http/axios';
const {Option} = Select;
const roomTag = [
  {
    name: '温馨',
    value: '温馨',
  },
  {
    name: '经济',
    value: '经济',
  },
  {
    name: '温泉',
    value: '温泉',
  },
  {
    name: '宽敞',
    value: '宽敞',
  },
  {
    name: '有窗户',
    value: '有窗户',
  },
];
const jsonToString = (arr) => {
  var s = '';
  if (arr instanceof Array || arr instanceof Object) {
    var isObj = 0;
    //check value type
    for (let key in arr) {
      if (isNaN(parseInt(key))) {
        //key is string
        isObj = 1;
      } else {
        //key is index , check sort
        var na = arr.length;
        var tmp = arr;
        //hack for ie
        arr = Array();
        for (var j = 0; j < na; j++) {
          if (typeof tmp[j] == 'undefined') {
            arr[j] = '';
          } else {
            arr[j] = tmp[j];
          }
        }
      }
      break;
    }
    for (let key in arr) {
      var value = arr[key];
      if (isObj) {
        if (s) {
          s += ',';
        }
        s += '"' + key + '":' + jsonToString(value);
      } else {
        if (s) {
          s += ',';
        }
        s += jsonToString(value);
      }
    }
    if (isObj) s = '{' + s + '}';
    else s = '[' + s + ']';
  } else {
    if (!isNaN(parseInt(arr))) {
      s += arr;
    } else {
      s = '"' + arr + '"';
    }
  }
  return s;
};
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default function Index() {
  const [img, setImg] = useState('');
  const [form] = Form.useForm();
  const [visible, setVisible] = useState({
    open: false,
    data: {
      roomName: '',
      id: '',
      roomSort: '',
      price: '',
    },
  });
  const [PicIdList, setPicIdList] = useState('');
  const {previewVisible, previewImage, fileList, previewTitle} = useState({});
  const [Btnevent, setBtnevent] = useState('');
  const [updata, setupdata] = useState('');

  const onCreate = (values) => {
    // values.uplowd = fileList;
    console.log('Received values of form: ', values);
    if (Btnevent === 'edit') {
      axios({
        //修改
        method: 'POST',
        url: '/room/updateRoom',
        data: {
          id: visible.data.id,
          room_address: values.room_address,
          room_name: values.room_name,
          room_price: values.room_price,
          password: '845252',
          title: values.title,
          tags: jsonToString(values.tags),
        },
      })
        .then((res) => {
          console.log(res);
          setupdata('up');
          message.success('修改房间成功');
        })
        .catch((err) => {
          console.log(err);
        });
      console.log('Received values of form: ', values);
    } else {
      axios({
        //添加
        method: 'POST',
        url: '/room/addRoom',
        data: {
          room_address: values.room_address,
          room_name: values.room_name,
          room_price: values.room_price,
          room_img: PicIdList,
          password: '845252',
          title: values.title,
          tags: jsonToString(values.tags),
        },
      })
        .then((res) => {
          message.success('添加房间成功');
          setupdata('addRoom');
          fileList = {};
          setPicIdList('');
        })
        .catch((err) => {
          console.log(err);
        });
    }
    setVisible({
      open: false,
      data: {
        id: '',
        room_address: '',
        room_name: '',
        room_price: '',
        title: '',
        tags: '',
        room_img:''
      },
    });
  };

  const fatherdata = (e, btn) => {
    console.log(e);
    if (btn === 'edit') {
      setBtnevent(btn);
      setImg(true);
      setVisible({
        open: true /*  */,
        data: {
          id: e.id,
          room_address: e.room_address,
          room_name: e.room_name,
          room_price: e.room_price,
          title: e.title,
          tags: e.tags,
          room_img:e.room_img
        },
      });
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{marginTop: 1}}>上传</div>
    </div>
  );
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
  };
  const handleChange = async (info) => {
    let fromData = await getBase64(info.file.originFileObj);
    axios({
      url: '/upload/tengxunFood',
      method: 'POST',
      data: {file: fromData},
    }).then((res) => {
      setPicIdList(res.data.fullpath);
    });
  };
  const rulst = [
    {
      required: true,
      message: '这里是必填哦!',
    },
  ];
  return (
    <>
      <Button
        style={{margin: '10px'}}
        onClick={() => {
          setImg(false);
          setVisible({
            open: true,
            data: {
              id: '',
              room_address: '',
              room_name: '',
              room_price: '',
              title: '',
              tags: undefined,
              room_img:''
            },
          });
        }}
      >
        添加房间
      </Button>
      <RoomTable fatherdata={fatherdata} updata={updata}></RoomTable>
      <Modal
        key={88}
        visible={visible.open}
        title="添加房间"
        okText="确定"
        cancelText="取消"
        // okButtonProps={{disabled: btnstau}}
        onCancel={() => {
          form.resetFields();
          setBtnevent('');
          setVisible({
            ...visible,
            open: false,
            data: {
              roomName: '',
              id: '',
              roomSort: '',
              price: '',
            },
          });
        }}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields(); //重置
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        {img ? (
          <div style={{margin: '20px 0'}}>
            菜品图片
            <img style={{width: '100px'}} src={visible.data.room_img} />
          </div>
        ) : (
          <div>
            上传菜品图片
            <Upload
              key={87}
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
            >
              {fileList && fileList.length >= 8 ? null : uploadButton}
            </Upload>
          </div>
        )}
        <Form
          key={200}
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={visible.data}
        >
          <Form.Item
            key={Math.random()}
            name="room_address"
            label="房间号"
            rules={rulst}
          >
            <Input key={Math.random()} />
          </Form.Item>
          <Form.Item
            key={Math.random()}
            name="title"
            label="房间名"
            rules={rulst}
          >
            <Select
              showSearch
              allowClear
              placeholder="选择房间名"
              key={Math.random()}
            >
              <Option value="点睛·温泉家庭房" key={Math.random()}>
                点睛·温泉家庭房
              </Option>
              <Option value="梨花汀舒适大床房" key={Math.random()}>
                梨花汀舒适大床房
              </Option>
              <Option value="沐风·豪华大床房" key={Math.random()}>
                沐风·豪华大床房
              </Option>
              <Option value="晒书·中式大床房" key={Math.random()}>
                晒书·中式大床房
              </Option>
              <Option value="吟诗·中式双床房" key={Math.random()}>
                吟诗·中式双床房
              </Option>
            </Select>
          </Form.Item>
          <Form.Item
            key={Math.random()}
            name="room_name"
            label="房间类型"
            rules={rulst}
          >
            <Select
              showSearch
              allowClear
              placeholder="选择房间类型"
              key={Math.random()}
            >
              <Option value="大床房" key={Math.random()}>
                大床房
              </Option>
              <Option value="标间" key={Math.random()}>
                标间
              </Option>
              <Option value="家庭房" key={Math.random()}>
                家庭房
              </Option>
              <Option value="双床" key={Math.random()}>
                双床
              </Option>
            </Select>
          </Form.Item>
          <Form.Item key={Math.random()} name="tags" label="房间标签">
            <Select mode="multiple" allowClear placeholder="选择房间标签">
              {roomTag.map((item) => {
                return (
                  <Option key={Math.random()} value={item.value}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            key={Math.random()}
            name="room_price"
            label="房间价格"
            rules={rulst}
          >
            <Input key={Math.random()} type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
